//
//  LBWComposeViewController.swift
//  weibo
//
//  Created by Limonwei on 15/12/12.
//  Copyright © 2015年 heima. All rights reserved.
//

//发布微博界面 包括头部视图 输入框 配图框 工具框

import UIKit
import SVProgressHUD
import AFNetworking

class LBWComposeViewController: UIViewController {

    //是否执行动画
    var isToolBarAnim: Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
    }
    
    //设置视图
    private func setupUI(){
        
        //添加头部视图
        setupNav()
        
        //添加子控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(composePictureView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.top.equalTo(textView).offset(100)
        }
        
        //设置属性
        toolBar.childButtonClickClosure = { [weak self] (type:LBWComposeToolBarButtonType) in
            
            switch type{
            case .Picture:
                self?.selectedPicture()
                
            case .Mention:
                print("@")
            case .Tread:
                print("#")
            case .Emotion:
               
                self?.switchKeyboard()
            case .Add:
                print("添加")

            }

        }
        
        //接收通知
        //监听键盘的弹出(通知) 有参数的时候一定要加冒号
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDidSelected:", name: LBWEmoticonButtonDidSelectedNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteBtnDidSelected", name: LBWMDeleteButtonDidSelectedNotification, object: nil)
    }
    
    //设置导航栏视图
    private func setupNav(){
        //设置左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Done, target: self, action: "back")
        
        //设置右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        //右边发送按钮默认不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置中间titleView
        navigationItem.titleView = titleView
    }
    
    //监听按钮点击
    @objc private func back() {
        //关闭键盘
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func emoticonDidSelected(noti: NSNotification){
        let emoticon = noti.userInfo!["emoticon"]! as! LBWEmoticon
        
        textView.inserEmoticon(emoticon)
    }
    
    @objc private func deleteBtnDidSelected(){
        //执行跟跟原生键盘上删除按钮一样的逻辑
        textView.deleteBackward()
    }
    
    @objc private func send(){
        //判断用户是发文字还是发图片微博
        if composePictureView.images.count > 0 {
            //图片微博
            upload()
            
        }else{
            //文字微博
            updata()
        }
    }
    
    //上传图片发送微博
    private func upload(){
        LBWNetworkTools.shareTool.upload(LBWUserAccountViewModel.shareAccount.accessToken!, status: textView.text!, image: composePictureView.images.first!) { (response, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败")
                return

            }
             SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    //发送文字微博
    private func updata(){
        LBWNetworkTools.shareTool.updata(LBWUserAccountViewModel.shareAccount.accessToken!, status: textView.emoticonText) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    //监听键盘frame的改变
    @objc private func keyboardWillChangeFrame(noti: NSNotification){
        
        //如果  isToolBarAnim 为 true 才执行动画
        if !isToolBarAnim{
            return
        }
        
        //取到键盘的结束位置
        let endRect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //取到动画执行时间
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        //把toolBar的底部改成endRect里面y的里面 设置约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(endRect.origin.y - self.view.height)
        }
        
        UIView.animateWithDuration(duration.doubleValue) { () -> Void in
            self.toolBar.layoutIfNeeded()
        }
        
    }

    
    
    //懒加载控件
    //1.发送按钮
    private lazy var sendButton: UIButton = {
    
        let button = UIButton()
        
        //添加按钮点击时间
        button.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        
        //设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
    
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        //设置不同状态的文字颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        
        //设置文字及其大小
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //指定大小
        button.size = CGSize(width: 45, height: 30)
        
        return button
        
    
    }()
    
    //2.中间titleView
    private lazy var titleView: UILabel = {
    
        let titleView = UILabel()
        
        if let name = LBWUserAccountViewModel.shareAccount.userAccount?.screen_name {
            
            //设置多行显示
            titleView.numberOfLines = 0
            //通过内容生成一个富文本对象
            let attrText = NSMutableAttributedString(string: "发微博\n\(name)")
            
            let range = (attrText.string as NSString).rangeOfString(name)
            
            //设置对应位置的字体大小
            let attrs = [
            
                NSFontAttributeName: UIFont.systemFontOfSize(14),
                NSForegroundColorAttributeName: UIColor.grayColor()
            
            ]
            attrText.addAttributes(attrs, range: range)
            
            //设置到label上去
            titleView.attributedText = attrText
        }else {
            titleView.text = "发微博"
        }
        
        //设置文字居中
        titleView.textAlignment = .Center
        
        //适配内容大小
        titleView.sizeToFit()
        
        return titleView
    
    
    }()
    
    //3.文字输入框
    
    private lazy var textView: LBWComposeTextView = {
       
        let textView = LBWComposeTextView()
        
        textView.font = UIFont.systemFontOfSize(16)
        
        textView.placeholder = "请输入想发的内容..."
        
        //设置代理监听文字改变
        textView.delegate = self
        
        //开启竖直方向的弹簧效果
        textView.alwaysBounceVertical = true
        
        return textView

    }()
    
    //4.工具条toolBar
    private lazy var toolBar: LBWComposeToolBar = LBWComposeToolBar(frame: CGRectZero)
    
    //5.配图视图
    private lazy var composePictureView: LBWComposePictureView = {
    
        let composePicture = LBWComposePictureView()
        
        //添加图片要调用的闭包
        
        composePicture.addImageClosure = { [weak self] in
    
            self?.selectedPicture()
            
        }
        composePicture.backgroundColor = self.textView.backgroundColor
    
        return composePicture
    }()
    
    //6.表情控件
    private lazy var emoticonKeyboard: LBWEmoticonLeyboard = {
    
        let keyboard = LBWEmoticonLeyboard()
        
        keyboard.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        
        return keyboard
    
    
    }()
}


//处理toolBar的按钮点击
extension LBWComposeViewController {
    
    //选择图片
    private func selectedPicture(){
        
        //弹出悬着照片的控制器
        let pickView = UIImagePickerController()
        
        //判断照相是否可用
        // let result = UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)
        //        // 判断照相机前后摄像头是否可用
        //        UIImagePickerController.isCameraDeviceAvailable(.Rear)
        // 是否允许编辑图片,默认不开启
        // pickerVC.allowsEditing = true
        pickView.delegate = self
        
        presentViewController(pickView, animated: true, completion: nil)
    }
    //切换键盘 系统键盘 表情键盘
    private func switchKeyboard(){
        
        isToolBarAnim = false
        //取消第一响应者
        textView.resignFirstResponder()
        //切换键盘
//        textView.inputView = (textView.inputView == nil) ? emoticonKeyboard : nil
        if textView.inputView == nil{
            textView.inputView = emoticonKeyboard
        }else{
            textView.inputView = nil
        }
        
        // 如果 textView.inputView 不为 nil 就代表当前是表情键盘
        toolBar.isEmoticonKeyboard = (textView.inputView != nil)
        // 将 isToolBarAnim 设置成 true ,就代表 成为第一响应者 的时候,需要执行动画

        isToolBarAnim = true
        
        //成为第一响应者
        textView.becomeFirstResponder()
        
        
    }
    
}

//选择图片控制器的代理方法
extension LBWComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        composePictureView.addImage(image)
        
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}


//文本视图TextView的代理方法
extension LBWComposeViewController: UITextViewDelegate {
    
    
    func textViewDidChange(textView: UITextView) {
        //当输入文字的时候大宋按钮才能点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //滚动回退键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}
















